﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dubs_Finder.Model
{
    internal class CyclicalFileBuffer
    {
        private FileWrapper[] buffer;
        private int curIndex = 0;
        private int size;

        internal CyclicalFileBuffer(int size)
        {
            this.buffer = new FileWrapper[size];
            this.size = size;
        }

        internal void addFile(FileWrapper fw)
        {
            this.buffer[curIndex] = fw;
            incrementIndex();
        }

        internal FileWrapper ContainsSimilar(FileWrapper fw)
        {
            int tmpIndex = getIndex(this.curIndex, 1);
            //Look for files with identical hashes
            while (tmpIndex != this.curIndex)
            {
                //Debug.WriteLine("Index: {0}", tmpIndex);
                FileWrapper tmpFile = buffer[tmpIndex];
                if (tmpFile != null && String.Equals(tmpFile.HashString, fw.HashString, StringComparison.OrdinalIgnoreCase)) return tmpFile;
                tmpIndex = getIndex(tmpIndex, 1);
            }
            //No files were found
            return null;
        }

        private int getIndex(int curIndex, int offset)
        {
            if (offset > curIndex) return this.size - (offset - curIndex);
            return curIndex - offset;
        }

        private void incrementIndex()
        {
            if (this.curIndex == this.size - 1) this.curIndex = 0;
            else this.curIndex++;
        }
    }
}
